﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ResourceLoadBalancer.WebServices.Contracts.Data;
using System.IO;
using System.Security.Cryptography;

namespace ResourceLoadBalancer.Client
{
    public class MD5Utility
    {

        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            StringBuilder sb = new StringBuilder();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);

            foreach (byte b in md5.ComputeHash(inputBytes))
            {
                sb.Append(b.ToString("x2").ToLower());
            }

            return sb.ToString();
        }


        public ResourceDataContract CalculateMD5Hash(FileInfo file)
        {
            ResourceDataContract resource = new ResourceDataContract();

            StringBuilder sb = new StringBuilder();

            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                SHA1 sha1 = new SHA1CryptoServiceProvider();

                using (FileStream fs = file.Open(FileMode.Open, FileAccess.Read,FileShare.ReadWrite))
                {
                    foreach (byte b in md5.ComputeHash(fs))
                    {
                        sb.Append(b.ToString("x2").ToLower());

                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                sb.Append("Unable to access file");
            }
            resource.Hash = sb.ToString();
            resource.SizeInBytes = file.Length;

            return resource;
        }

        public ResourceDataContract CalculateMD5Hash(byte[] file)
        {
            ResourceDataContract resource = new ResourceDataContract();

            StringBuilder sb = new StringBuilder();

            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                SHA1 sha1 = new SHA1CryptoServiceProvider();


                byte[] result = md5.ComputeHash(file);


                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < result.Length; i++)
                {
                    sb.Append(result[i].ToString("x2"));
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                sb.Append("Unable to access file");
            }
            resource.Hash = sb.ToString();
            resource.SizeInBytes = file.Length;

            return resource;
        }
    }


}
